﻿// Decompiled with JetBrains decompiler
// Type: DnProcessSimulateCommands.ModularFixture.CApMFAdministratorManager
// Assembly: DnProcessSimulateCommands, Version=2402.0.0.890, Culture=neutral, PublicKeyToken=null
// MVID: A885D881-AEDF-447E-852A-6F13102E089C
// Assembly location: C:\Program Files\Tecnomatix_2402\eMPower\DotNetCommands\DnProcessSimulateCommands.dll

using C1.Win.C1FlexGrid;
using EMPMODELLib;
using EMPTYPELIBRARYLib;
using EngineeringInternalExtension;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Resources;
using System.Windows.Forms;
using Tecnomatix.Engineering;
using Tecnomatix.Planning;


namespace DnProcessSimulateCommands.ModularFixture;

public class CApMFAdministratorManager
{
  private CUiMFConfigurationsGridWrapper m_grid;
  private CApMFConfigurationData m_configurationData;
  private bool m_configurationLoaded;
  private TxCompoundResource m_configurationResource;
  private ArrayList m_displayedOrigins;

  internal event CApMFAdministratorManager.MFAdministratorManager_LoadConfigurationEventHandler ConfigurationLoaded;

  internal CApMFAdministratorManager(CUiMFConfigurationsGridWrapper grid)
  {
    this.m_grid = grid;
    this.m_configurationLoaded = false;
    this.m_configurationResource = (TxCompoundResource) null;
    this.m_displayedOrigins = new ArrayList();
  }

  internal void SetConfigurationData(string name, int type, string usage, string bitmap)
  {
    switch (type)
    {
      case 0:
        this.m_configurationData = (CApMFConfigurationData) new CApMFConfigurationTypeData(name, usage, bitmap);
        break;
      case 1:
        this.m_configurationData = (CApMFConfigurationData) new CApMFUnitTypeData(name, bitmap);
        break;
      case 2:
        this.m_configurationData = (CApMFConfigurationData) new CApMFFixtureBaseTypeData(name, bitmap);
        break;
    }
  }

  internal void UpdateConfigurationData(string bitmap)
  {
    this.m_configurationData.BitmapFile = bitmap;
  }

  internal void CreateRootNode(string rootName) => this.m_grid.CreateRoot(rootName, 0);

  internal void AddPrototypeNodeToGrid(ITxObject newObject, int rowIndex)
  {
    if ((newObject as TxPlanningObject).IsDerivedFromPlanningType("UnitConfigurationPrototype"))
      this.LoadConfigurationChildren(newObject as TxPlanningObject, 0, rowIndex);
    else
      this.m_grid.AddPrototypeNode(newObject);
  }

  internal void AddPrototypeNodeToGrid(ITxObject newObject)
  {
    this.AddPrototypeNodeToGrid(newObject, ((C1FlexGridBase) this.m_grid).RowSel);
  }

  internal void LoadFromCompoundResource(TxCompoundResource compoundRes)
  {
    this.LoadFromCompoundResource((ITxObject) compoundRes, ((C1FlexGridBase) this.m_grid).RowSel);
  }

  internal bool SaveConfiguration()
  {
    ((C1FlexGridBase) this.m_grid).FinishEditing();
    CApMFGridRow gridRow = this.m_grid.GetGridRow(1);
    EmpObjectKey parent;
    parent.objectId = CApMFAdminUtils.m_targetLibraryId;
    bool ems = this.saveToEMS(gridRow, parent);
    if (ems)
      this.m_configurationData.SaveAttributesToEms(gridRow.PrototypeId);
    return ems;
  }

  internal bool LoadConfiguration(TxPlanningObject planningObject, int rowIndex)
  {
    bool flag = true;
    EmpContext empContext;
    empContext.sessionId = TxApplication.ActiveDocument.eMSSessionId;
    EmpToolPrototypeClass toolPrototypeClass = new EmpToolPrototypeClass();
    TxEmsServicesProvider servicesProvider1 = planningObject.PlatformServicesProvider as TxEmsServicesProvider;
    EmpObjectKey empObjectKey;
    empObjectKey.objectId = servicesProvider1.InternalId;
    CApMFAdminUtils.m_targetLibraryId = toolPrototypeClass.GetCollections(ref empContext, ref empObjectKey)[0].objectId;
    this.DeleteConfigurationResource();
    this.m_grid.CreateRoot(TxObjectEx.GetPlanningObjectName((ITxObject) planningObject), servicesProvider1.InternalId);
    this.SetConfigurationData(planningObject);
    foreach (ITxPlanningObject objectDescendant in (Collection<ITxObject>) CApMFAdminUtils.GetPlanningObjectDescendants(planningObject))
    {
      TxEmsServicesProvider servicesProvider2 = objectDescendant.PlatformServicesProvider as TxEmsServicesProvider;
      if (!this.LoadConfigurationChildren((TxPlanningObject) CApMFAdminUtils.GetPrototype(objectDescendant), servicesProvider2.InternalId, 1))
      {
        flag = false;
        break;
      }
    }
    if (flag)
    {
      this.IsConfigurationLoaded = true;
      this.ConfigurationLoaded();
    }
    return flag;
  }

  internal bool LoadConfigurationChildren(
    TxPlanningObject planningObject,
    int instanceId,
    int rowIndex)
  {
    int internalId = ((TxEmsServicesProvider) planningObject.PlatformServicesProvider).InternalId;
    if (planningObject.IsDerivedFromPlanningType("UnitConfigurationPrototype"))
      this.m_grid.AddCompoundResourceNode(TxObjectEx.GetPlanningObjectName((ITxObject) planningObject), internalId, rowIndex, instanceId, 0);
    else if (planningObject.IsDerivedFromPlanningType("UnitConfigurationVarPrototype"))
    {
      this.m_grid.AddVariationNode(TxObjectEx.GetPlanningObjectName((ITxObject) planningObject), rowIndex, internalId, instanceId);
      planningObject = ((Collection<ITxObject>) CApMFAdminUtils.GetPlanningObjectDescendants(planningObject))[0] as TxPlanningObject;
      planningObject = CApMFAdminUtils.GetPrototype((ITxPlanningObject) planningObject) as TxPlanningObject;
    }
    else if (planningObject.IsDerivedFromPlanningType("ToolPrototype"))
      this.m_grid.AddPrototypeNode((ITxObject) planningObject, instanceId, rowIndex, 0);
    rowIndex += this.m_grid.NodeGetNumberOfChildren(rowIndex);
    foreach (ITxPlanningObject objectDescendant in (Collection<ITxObject>) CApMFAdminUtils.GetPlanningObjectDescendants(planningObject))
    {
      TxEmsServicesProvider servicesProvider = objectDescendant.PlatformServicesProvider as TxEmsServicesProvider;
      this.LoadConfigurationChildren((TxPlanningObject) CApMFAdminUtils.GetPrototype(objectDescendant), servicesProvider.InternalId, rowIndex);
    }
    return true;
  }

  internal void DisplayConfiguration()
  {
    TxTransformation txTransformation = new TxTransformation();
    TxObjectList prototypesFromGrid = this.GetPrototypesFromGrid();
    if (((Collection<ITxObject>) prototypesFromGrid).Count > 0)
    {
      string[] attributes = new string[1]{ "weight" };
      CApMFAdminUtils.ImportFields(prototypesFromGrid, attributes, "weight");
    }
    using (TxCompoundResourceCreationData resourceCreationData = new TxCompoundResourceCreationData(this.ConfigurationData.Name, txTransformation))
      this.m_configurationResource = TxApplication.ActiveDocument.PhysicalRoot.CreateCompoundResource(resourceCreationData);
    bool flag = true;
    for (int index = this.m_grid.GetNodeFirstChildIndex(1); index > 0 & flag; index = this.m_grid.GetNodeNextSiblingIndex(index))
      flag = this.DisplayConfigurationChildren(index, this.m_configurationResource);
    if (flag)
    {
      this.DisplayOrigins();
      this.m_configurationResource.Display();
    }
    else
    {
      this.DeleteConfigurationResource();
      ResourceManager resourceManager = new ResourceManager("DnProcessSimulateCommands.ModularFixture.ConfigurationAdministrator.Res.StringTable", this.GetType().Assembly);
      int num = (int) TxMessageBox.Show(resourceManager.GetString("WRONG_SYSTEM_ROOT_MESSAGE"), resourceManager.GetString("CMD_CONFIGURATION_ADMINISTRATOR_NAME"), MessageBoxButtons.OK, MessageBoxIcon.Hand);
    }
  }

  internal void DeleteConfigurationResource()
  {
    if (TxCompoundResource.op_Inequality(this.m_configurationResource, (ITxObject) null) && !this.m_configurationResource.IsValid())
      this.m_configurationResource = (TxCompoundResource) null;
    foreach (TxFrame displayedOrigin in this.m_displayedOrigins)
    {
      if (displayedOrigin.IsValid())
        displayedOrigin.Delete();
    }
    this.m_displayedOrigins.Clear();
    if (!TxCompoundResource.op_Inequality(this.m_configurationResource, (ITxObject) null))
      return;
    this.m_configurationResource.Delete();
    this.m_configurationResource = (TxCompoundResource) null;
    TxApplication.RefreshDisplay();
  }

  internal void SelectCell(int row, int col) => ((C1FlexGridBase) this.m_grid).Select(row, col);

  internal bool saveToEMS(CApMFGridRow row, EmpObjectKey parent)
  {
    bool ems1 = true;
    int ems2 = row.SaveNodeToEms(parent);
    ArrayList childrenIdsList = new ArrayList();
    CApMFGridRow row1 = (CApMFGridRow) null;
    if (ems2 == 0)
      ems1 = false;
    else
      row1 = this.m_grid.GetNodeFirstChild(row);
    for (; row1 != null & ems1; row1 = this.m_grid.GetNodeNextSibling(row1))
    {
      EmpObjectKey parent1;
      parent1.objectId = ems2;
      ems1 = this.saveToEMS(row1, parent1);
      childrenIdsList.Add((object) row1.InstanceId);
    }
    if (ems1 && row is CApMFVariationGridRow)
      ((CApMFVariationGridRow) row).RemoveDeletedOptions();
    if (ems1 && !(row is CApMFPrototypeGridRow))
      CApMFAdminUtils.RemoveDeletedObjects(ems2, childrenIdsList);
    return ems1;
  }

  private void DisplayOrigins()
  {
    if (this.ConfigurationData is CApMFConfigurationTypeData)
    {
      TxFrame frame = TxApplication.ActiveDocument.PhysicalRoot.CreateFrame(new TxFrameCreationData(this.ConfigurationData.Name + new ResourceManager("DnProcessSimulateCommands.ModularFixture.ConfigurationAdministrator.Res.StringTable", this.GetType().Assembly, (Type) null).GetString("FIXTURE_UNIT_ORIGIN_NAME"), (this.ConfigurationData as CApMFConfigurationTypeData).FixtureUnitOrigin));
      frame.Color = TxColor.TxColorRed;
      this.m_displayedOrigins.Add((object) frame);
    }
    ArrayList gridRows = this.m_grid.GridRows;
    int num = 0;
    for (int index = 1; index < gridRows.Count; ++index)
    {
      if (gridRows[index] is CApMFPrototypeGridRow prototypeGridRow)
      {
        if (TxTransformation.op_Inequality(prototypeGridRow.PlacementOrigin, (TxTransformation) null))
        {
          string str1 = new ResourceManager("DnProcessSimulateCommands.ModularFixture.ConfigurationAdministrator.Res.StringTable", this.GetType().Assembly, (Type) null).GetString("PLACEMENT_ORIGIN_NAME");
          TxTransformation txTransformation = TxTransformation.op_Multiply(this.m_grid.GetLocationOfRowRelativeToRoot(index), prototypeGridRow.PlacementOrigin);
          string str2 = this.ConfigurationData.Name + str1;
          if (num > 0)
            str2 = $"{str2}_{num.ToString()}";
          TxFrame frame = TxApplication.ActiveDocument.PhysicalRoot.CreateFrame(new TxFrameCreationData(str2, txTransformation));
          frame.Color = TxColor.TxColorBlue;
          this.m_displayedOrigins.Add((object) frame);
          ++num;
        }
        if (TxTransformation.op_Inequality(prototypeGridRow.IntermediateUnitPlacementPoint, (TxTransformation) null))
        {
          TxFrame frame = TxApplication.ActiveDocument.PhysicalRoot.CreateFrame(new TxFrameCreationData(this.ConfigurationData.Name + new ResourceManager("DnProcessSimulateCommands.ModularFixture.ConfigurationAdministrator.Res.StringTable", this.GetType().Assembly, (Type) null).GetString("INTERMEDIATE_UNIT_PLACEMENT_POINT_NAME"), TxTransformation.op_Multiply(this.m_grid.GetLocationOfRowRelativeToRoot(index), prototypeGridRow.IntermediateUnitPlacementPoint)));
          frame.Color = TxColor.TxColorBlack;
          this.m_displayedOrigins.Add((object) frame);
        }
      }
    }
  }

  private bool DisplayConfigurationChildren(int row, TxCompoundResource parentResource)
  {
    bool flag = true;
    CApMFGridRow gridRow = this.m_grid.GetGridRow(row);
    switch (gridRow)
    {
      case CApMFCompoundResGridRow _:
        CApMFCompoundResGridRow compoundResGridRow = gridRow as CApMFCompoundResGridRow;
        TxTransformation txTransformation = TxTransformation.op_Multiply(parentResource.AbsoluteLocation, compoundResGridRow.Location);
        using (TxCompoundResourceCreationData resourceCreationData = new TxCompoundResourceCreationData(compoundResGridRow.Name, txTransformation))
        {
          TxCompoundResource compoundResource = parentResource.CreateCompoundResource(resourceCreationData);
          for (int index = this.m_grid.GetNodeFirstChildIndex(row); index > 0 & flag; index = this.m_grid.GetNodeNextSiblingIndex(index))
            flag = this.DisplayConfigurationChildren(index, compoundResource);
          break;
        }
      case CApMFPrototypeGridRow _:
        CApMFPrototypeGridRow prototypeGridRow = gridRow as CApMFPrototypeGridRow;
        if (!Directory.Exists(prototypeGridRow.PrototypePath))
        {
          flag = false;
          prototypeGridRow.PrototypePath = "";
          break;
        }
        ITxComponent itxComponent = TxApplication.ActiveDocument.PhysicalRoot.InsertComponent(new TxInsertComponentCreationData(prototypeGridRow.Name, prototypeGridRow.PrototypePath)
        {
          Prototype = prototypeGridRow.Prototype
        });
        ITxObjectCollection objectCollection = (ITxObjectCollection) parentResource;
        if (objectCollection.CanBeAdded((ITxObject) itxComponent))
          objectCollection.AddObject((ITxObject) itxComponent);
        (itxComponent as ITxLocatableObject).AbsoluteLocation = TxTransformation.op_Multiply(parentResource.AbsoluteLocation, prototypeGridRow.Location);
        break;
      case CApMFVariationGridRow _:
        CApMFVariationGridRow variationGridRow = gridRow as CApMFVariationGridRow;
        for (int index = this.m_grid.GetNodeFirstChildIndex(row); index > 0 & flag; index = this.m_grid.GetNodeNextSiblingIndex(index))
          flag = this.DisplayConfigurationChildren(index, parentResource);
        break;
    }
    return flag;
  }

  private void LoadFromCompoundResource(ITxObject resource, int row)
  {
    switch (resource)
    {
      case TxCompoundResource _:
        TxCompoundResource compoundResource = resource as TxCompoundResource;
        TxEmsServicesProvider servicesProvider1 = compoundResource.PlanningRepresentation.PlatformServicesProvider as TxEmsServicesProvider;
        this.m_grid.AddCompoundResourceNode(compoundResource.Name, 0, row, 0, servicesProvider1.InternalId);
        row += this.m_grid.NodeGetNumberOfChildren(row);
        TxNoTypeFilter txNoTypeFilter = new TxNoTypeFilter();
        TxObjectList directDescendants = compoundResource.GetDirectDescendants((ITxTypeFilter) txNoTypeFilter);
        ITxPlanningObject planningRepresentation = compoundResource.PlanningRepresentation;
        using (IEnumerator<ITxObject> enumerator = ((Collection<ITxObject>) directDescendants).GetEnumerator())
        {
          while (enumerator.MoveNext())
            this.LoadFromCompoundResource(enumerator.Current, row);
          break;
        }
      case ITxComponent _:
        ITxProcessModelObject processModelObject = resource as ITxProcessModelObject;
        ITxPlanningObject prototype = CApMFAdminUtils.GetPrototype(processModelObject.PlanningRepresentation);
        TxEmsServicesProvider servicesProvider2 = processModelObject.PlanningRepresentation.PlatformServicesProvider as TxEmsServicesProvider;
        this.m_grid.AddPrototypeNode((ITxObject) prototype, 0, row, servicesProvider2.InternalId);
        break;
    }
  }

  private TxObjectList GetPrototypesFromGrid()
  {
    TxObjectList prototypesFromGrid = new TxObjectList();
    ArrayList gridRows = this.m_grid.GridRows;
    TxEmsGlobalServicesProvider servicesProvider = new TxEmsGlobalServicesProvider();
    for (int index = 1; index < gridRows.Count; ++index)
    {
      CApMFGridRow capMfGridRow = gridRows[index] as CApMFGridRow;
      if (capMfGridRow is CApMFPrototypeGridRow)
      {
        ITxPlanningObject objectByInternalId = servicesProvider.GetObjectByInternalId(capMfGridRow.PrototypeId);
        ((Collection<ITxObject>) prototypesFromGrid).Add((ITxObject) objectByInternalId);
      }
    }
    return prototypesFromGrid;
  }

  private void SetConfigurationData(TxPlanningObject planningObject)
  {
    string planningObjectName = TxObjectEx.GetPlanningObjectName((ITxObject) planningObject);
    TxEmsServicesProvider servicesProvider = planningObject.PlatformServicesProvider as TxEmsServicesProvider;
    EmpContext empContext;
    empContext.sessionId = TxApplication.ActiveDocument.eMSSessionId;
    switch ((string) ((IEmpObject) new EmpObjectClass()).GetField(ref empContext, ref new EmpObjectKey()
    {
      objectId = servicesProvider.InternalId
    }, "ConfigurationType").Value)
    {
      case "Configuration":
        this.m_configurationData = (CApMFConfigurationData) new CApMFConfigurationTypeData(planningObjectName);
        break;
      case "FixtureBase":
        this.m_configurationData = (CApMFConfigurationData) new CApMFFixtureBaseTypeData(planningObjectName);
        break;
      case "Unit":
        this.m_configurationData = (CApMFConfigurationData) new CApMFUnitTypeData(planningObjectName);
        break;
    }
    this.m_configurationData.LoadAttributesFromEms(servicesProvider.InternalId);
  }

  internal CApMFConfigurationData ConfigurationData
  {
    get => this.m_configurationData;
    set => this.m_configurationData = value;
  }

  internal bool IsConfigurationLoaded
  {
    get => this.m_configurationLoaded;
    set => this.m_configurationLoaded = value;
  }

  internal delegate void MFAdministratorManager_LoadConfigurationEventHandler();

  internal enum ConfigurationTypeEnum
  {
    Configuration,
    Unit,
    FixtureBase,
  }
}
